package com.dmall.chapter06.section05;

public class LeetCode130 {

    private int R, C;
    private boolean[][] visited;
    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public void solve(char[][] board) {
        if (board == null) {
            return;
        }
        R = board.length;
        if (R == 0) {
            return;
        }
        C = board[0].length;
        if (C == 0) {
            return;
        }
        visited = new boolean[R][C];
        for (int i = 0; i < R; i++) {
            if (board[i][0] == 'O') {
                dfs(board, i, 0);
            }
            if (board[i][C - 1] == 'O') {
                dfs(board, i, C - 1);
            }
        }

        for (int i = 0; i < C; i++) {
            if (board[0][i] == 'O') {
                dfs(board, 0, i);
            }
            if (board[R - 1][i] == 'O') {
                dfs(board, R - 1, i);
            }
        }

        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (!visited[i][j] && board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }
    }

    private void dfs(char[][] board, int x, int y) {
        visited[x][y] = true;
        for (int i = 0; i < dirs.length; i++) {
            int nextx = x + dirs[i][0];
            int nexty = y + dirs[i][1];
            if (inArea(nextx, nexty) && !visited[nextx][nexty] && board[nextx][nexty] == 'O') {
                dfs(board, nextx, nexty);
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        char[][] board = {
                {'X', 'X', 'X', 'X'},
                {'X', 'O', 'O', 'X'},
                {'X', 'X', 'O', 'X'},
                {'X', 'O', 'X', 'X'}
        };
        LeetCode130 leetCode130 = new LeetCode130();
        leetCode130.solve(board);
        for (char[] chars : board) {
            for (char c : chars) {
                System.out.print(c + " ");
            }
            System.out.println();
        }
    }
}
